package org.zxp.thread.communication.piped;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.util.stream.Collectors;

/**
 * @program: zxp-thread-test
 * @description: 接收线程
 * @author: X-Pacific zhang
 * @create: 2019-05-18 16:54
 **/
public class R_Thread implements Runnable {
    private PipedInputStream pipedInputStream;

    public R_Thread(PipedInputStream pipedInputStream) {
        this.pipedInputStream = pipedInputStream;
    }


    @Override
    public void run() {
//        System.out.println("yunxing ");
//        while(pipedInputStream != null){
//            String msg = new BufferedReader(
//                    new InputStreamReader(
//                            pipedInputStream
//                    )
//            ).lines().collect(Collectors.joining());
//            System.out.println("在线程中===="+msg);
//            try {
//                pipedInputStream.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }

        int len = -1;
        byte[] buffer = new byte[1024];
        try {
            //read(buffer, 0, buffer.length)函数作用有两个：
            //(1)若有buffer.length个数据可读，则返回buffer.length个数据；
            //   否则读取当前可读的所有数据，个数小于buffer.length;
            //(2)若没有数据可读，则让读进程等待(见read()函数)
            while ((len = pipedInputStream.read(buffer)) != -1) {//接收到结束后才终止
                System.out.println(new String(buffer, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                System.out.println("ipedInputStream.close");
                pipedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
